import { login, logout } from '@/http/module/oauth'
import { getUserInfo, updatePassword } from '@/http/module/user'
import { clearLoginInfo } from '@/utils'

// 用户基本信息
export default {
	namespaced: true,
	state: {
		id: 0,
		nickName: '',
		userName: '',
		headUrl: '',
		email: '',
		sex: 0,
		cover: '',
		motto: '',
		root: false,
		login: false
	},
	mutations: {
		SET_OBJECT: (state, obj) => {
			for (let [key, value] of Object.entries(obj)) {
				state[key] = value
			}
		},
		SET_ID: (state, id) => {
			state.id = id
		},
		SET_NICKNAME: (state, nickName) => {
			state.nickName = nickName
		},
		SET_USERNAME: (state, userName) => {
			state.userName = userName
		},
		SET_HEADURL: (state, headUrl) => {
			state.headUrl = headUrl
		},
		SET_EMAIL: (state, email) => {
			state.email = email
		},
		SET_SEX: (state, sex) => {
			state.sex = sex
		},
		SET_ROOT: (state, root) => {
			state.root = root
		},
		SET_LOGIN: (state, login) => {
			state.login = login
		}
	},
	actions: {
		getUserInfo({ commit, state }) {
			return new Promise((resolve, reject) => {
			  getUserInfo().then(res => {
			    let data = res.data
			    commit('SET_OBJECT', data)
				commit('SET_LOGIN', data.id != 0)
			    resolve(res)
			  }).catch(error => {
				commit('SET_LOGIN', false)
			    reject(error)
			  })
			})
		},
		login({ commit, state }, dataForm) {
			return new Promise((resolve, reject) => {
				login(dataForm).then(res => {
					commit('SET_LOGIN', true)
					resolve(res)
				}).catch(error => {
					reject(error)
				})
				
			})
		},
		logout({ commit, state }) {
			return new Promise((resolve, reject) => {
				logout().then(res => {
					commit('SET_OBJECT', {
						id: 0,
						nickName: '',
						userName: '',
						headUrl: '',
						email: '',
						sex: 0,
						cover: '',
						motto: '',
						root: false
					})
					commit('SET_LOGIN', false)
					clearLoginInfo()
					resolve(res)
				}).catch(error => {
					reject(error)
				})
			})
		},
		updatePassword({ commit, state, dispatch }, dataForm) {
			return new Promise((resolve, reject) => {
				updatePasswordApi(dataForm).then(res => {
					commit('SET_OBJECT', {
						id: 0,
						nickName: '',
						userName: '',
						headUrl: '',
						email: '',
						sex: 0,
						cover: '',
						motto: '',
						root: false
					})
					clearLoginInfo()
					dispatch('common/UpdateMainTabs', [], { root: true })
					resolve(res)
				}).catch(error => {
					reject(error)
				})
			})
		}
	}
}
